<!DOCTYPE html>
<html lang=en>
<head>
	
	
        <meta name="baidu-site-verification" content="MlP2pxH3Vl" />
    
	
        <meta name="google-site-verification" content="45SJBg2HD_qTefbPJZZNWWaF-0sEwz_3sR_qo0HEp-M" />
    
    <meta charset="utf-8">
    
    <title>Java7新特性：try-with-resources自动关闭资源 | 东写西读</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="try-with-resources是Java7中新增特性，它允许在try关键字后跟一对圆括号，括号内可初始化一个或多个资源，try语句会在代码块执行完后自动关闭资源。">
<meta property="og:type" content="article">
<meta property="og:title" content="Java7新特性：try-with-resources自动关闭资源">
<meta property="og:url" content="http://menote.info/2016/04/21/Java7新特性：try-with-resources自动关闭资源/index.html">
<meta property="og:site_name" content="东写西读">
<meta property="og:description" content="try-with-resources是Java7中新增特性，它允许在try关键字后跟一对圆括号，括号内可初始化一个或多个资源，try语句会在代码块执行完后自动关闭资源。">
<meta property="og:updated_time" content="2017-04-24T02:27:59.438Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java7新特性：try-with-resources自动关闭资源">
<meta name="twitter:description" content="try-with-resources是Java7中新增特性，它允许在try关键字后跟一对圆括号，括号内可初始化一个或多个资源，try语句会在代码块执行完后自动关闭资源。">
    

    
        <link rel="alternate" href="https://minibox.coding.me/atom.xml" title="东写西读" type="application/atom+xml" />
    

    
        <link rel="icon" href="/css/images/fav.png# path to favicon" />
    

    <link rel="stylesheet" href="/libs/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/libs/open-sans/styles.css">
    <link rel="stylesheet" href="/libs/source-code-pro/styles.css">

    <link rel="stylesheet" href="/css/style.css">

    <script src="/libs/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/libs/lightgallery/css/lightgallery.min.css">
    
    
        <link rel="stylesheet" href="/libs/justified-gallery/justifiedGallery.min.css">
    
    
    
    


</head>

<body>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/" id="logo">
                <i class="logo"></i>
                <span class="site-title">东写西读</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/."><i class="fa fa-home"></i>Home</a>
                
                    <a class="main-nav-link" href="/archives"><i class="fa fa-archive"></i>Archives</a>
                
                    <a class="main-nav-link" href="/categories"><i class="fa fa-folder"></i>Categories</a>
                
                    <a class="main-nav-link" href="/tags"><i class="fa fa-tags"></i>Tags</a>
                
                    <a class="main-nav-link" href="/about"><i class="fa fa-user"></i>About</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="/css/images/st.png" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="Search" />
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="Type something..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: 'Posts',
            PAGES: 'Pages',
            CATEGORIES: 'Categories',
            TAGS: 'Tags',
            UNTITLED: '(Untitled)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td><a class="main-nav-link" href="/."><i class="fa fa-home"><span class="nav-link-text">Home</span></a></td>
                
                    <td><a class="main-nav-link" href="/archives"><i class="fa fa-archive"><span class="nav-link-text">Archives</span></a></td>
                
                    <td><a class="main-nav-link" href="/categories"><i class="fa fa-folder"><span class="nav-link-text">Categories</span></a></td>
                
                    <td><a class="main-nav-link" href="/tags"><i class="fa fa-tags"><span class="nav-link-text">Tags</span></a></td>
                
                    <td><a class="main-nav-link" href="/about"><i class="fa fa-user"><span class="nav-link-text">About</span></a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="Search" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="/css/images/st.png" />
            <h2 id="name">Mickole Chou</h2>
            <h3 id="title">Developer &amp; Writer</h3>
            <span id="location"><i class="fa fa-map-marker"></i>Chengdu, China</span>
            <a id="follow" target="_blank" href="https://github.com/mickolechou">FOLLOW</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                9
                <span>posts</span>
            </div>
            <div class="article-info-block">
                13
                <span>tags</span>
            </div>
        </div>
        
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="https://github.com/mickolechou" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="weibo" class=tooltip>
                            <i class="fa fa-weibo"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="weixin" class=tooltip>
                            <i class="fa fa-weixin"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="https://minibox.coding.me/atom.xml" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
        
    </div>
</aside>

            
            <section id="main"><article id="post-Java7新特性：try-with-resources自动关闭资源" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
            <header class="article-header">
                
    
        <h1 class="article-title" itemprop="name">
            Java7新特性：try-with-resources自动关闭资源
        </h1>
    

                
                    <div class="article-meta">
                        
    <div class="article-date">
        <i class="fa fa-calendar"></i>
        <a href="/2016/04/21/Java7新特性：try-with-resources自动关闭资源/">
            <time datetime="2016-04-21T08:42:46.000Z" itemprop="datePublished">2016-04-21</time>
        </a>
    </div>


                        
    <div class="article-category">
    	<i class="fa fa-folder"></i>
        <a class="article-category-link" href="/categories/java/">java</a>
    </div>

                        
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/tags/AutoCloseable/">AutoCloseable</a>, <a class="tag-link" href="/tags/Closeable/">Closeable</a>, <a class="tag-link" href="/tags/try-with-resources/">try-with-resources</a>
    </div>

                    </div>
                
            </header>
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
                <div id="toc" class="toc-article">
                <strong class="toc-title">Catalogue</strong>
                    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#try-with-resources"><span class="toc-number">1.</span> <span class="toc-text">try-with-resources</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#概念"><span class="toc-number">1.1.</span> <span class="toc-text">概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#示例代码"><span class="toc-number">1.2.</span> <span class="toc-text">示例代码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#异常测试"><span class="toc-number">1.3.</span> <span class="toc-text">异常测试</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Closeable和AutoColseable接口"><span class="toc-number">2.</span> <span class="toc-text">Closeable和AutoColseable接口</span></a></li></ol>
                </div>
            
            <blockquote>
<p>try-with-resources是Java7中新增特性，它允许在try关键字后跟一对圆括号，括号内可初始化一个或多个资源，try语句会在代码块执行完后自动关闭资源。</p>
</blockquote>
<a id="more"></a>
<h2 id="try-with-resources"><a href="#try-with-resources" class="headerlink" title="try-with-resources"></a>try-with-resources</h2><h3 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h3><p>在Java7之前，某些稀缺资源（如数据库连接、网络连接，IO流）使用后必须在finally语句中手动关闭，否则可能造成资源泄露、浪费，资源使用一般流程如下形式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">try</span> &#123;</div><div class="line">    <span class="comment">//资源使用</span></div><div class="line">&#125; <span class="keyword">catch</span>(Exception e) &#123;</div><div class="line">    <span class="comment">//异常处理</span></div><div class="line">&#125; <span class="keyword">finally</span> &#123;</div><div class="line">    <span class="comment">//关闭资源</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>为解决以上问题，Java7中新增try-with-resources特性。它允许在try关键字后跟一对圆括号，括号内可初始化一个或多个资源，try语句会在代码块执行完后自动关闭资源。资源使用流程如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">try</span> (Resource res = ) &#123;</div><div class="line">    <span class="comment">//使用资源</span></div><div class="line">&#125; <span class="keyword">catch</span> (Exception e) &#123;</div><div class="line">    <span class="comment">//异常处理</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>try-with-resources特性会在try代码块执行完后自动关闭所有资源，无需在finally中显示调用close()方法手动关闭，一来简洁了代码，二来以免忘记关闭。<br>try-with-resource也可以有catch和finally块，只是执行时机是在try-with-resource之后。</p>
<p>为保证try能正常自动关闭资源，要求资源：</p>
<ol>
<li>被关闭资源类必须实现autoClosable接口或者是Closable接口</li>
<li>需要自动关闭的资源必须在try后面圆括号内声明</li>
<li>资源自动关闭顺序与声明顺序相反</li>
</ol>
<h3 id="示例代码"><a href="#示例代码" class="headerlink" title="示例代码"></a>示例代码</h3><p>使用实例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AutoCloseTest</span> </span>&#123;</div><div class="line">    </div><div class="line">    <span class="meta">@Test</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testTryWithResource</span><span class="params">()</span> </span>&#123;</div><div class="line"></div><div class="line">        <span class="keyword">try</span>(Resource1 re1 = <span class="keyword">new</span> Resource1(); Resource2 re2 = <span class="keyword">new</span> Resource2()) &#123;</div><div class="line">            re1.doThing();</div><div class="line">            re2.doThing();</div><div class="line"></div><div class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Resource1</span> <span class="keyword">implements</span> <span class="title">AutoCloseable</span> </span>&#123;</div><div class="line"></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doThing</span><span class="params">()</span> </span>&#123;</div><div class="line">            System.out.println(<span class="string">"resource1 do something"</span>);</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="meta">@Override</span></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">close</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">            System.out.println(<span class="string">"close resource1"</span>);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Resource2</span> <span class="keyword">implements</span> <span class="title">AutoCloseable</span> </span>&#123;</div><div class="line"></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doThing</span><span class="params">()</span> </span>&#123;</div><div class="line">            System.out.println(<span class="string">"resource2 do something"</span>);</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="meta">@Override</span></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">close</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">            System.out.println(<span class="string">"close resource2"</span>);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>执行结果：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">resource1 <span class="keyword">do</span> something</div><div class="line">resource2 <span class="keyword">do</span> something</div><div class="line">close resource2</div><div class="line">close resource1</div></pre></td></tr></table></figure></p>
<p>可见资源关闭顺序与初始化顺序相反。</p>
<h3 id="异常测试"><a href="#异常测试" class="headerlink" title="异常测试"></a>异常测试</h3><p>Java7 以前如果try语句块和finally同时都抛出异常则只会抛出 finally  块中的异常，不会抛出try块中异常。这样经常会导致得到的异常信息不是调用程序想要得到的。</p>
<p>Java7 及以后版本中如果采用try-with-resource机制，如果在try-with-resource 声明中抛出异（可能是文件无法打或都文件无法关闭），同事try语句块中也抛出异常，则首先抛出try块中异常，同时try-with-resource抛出的异常会使用addSuppressed方法，将之前的异常记录下来。我们可以在自己的代码中调用getSuppressed方法去获取异常列表并处理。</p>
<p>采用try-with-resource机制抛异常测试：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Test</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testThrowException2</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">    <span class="keyword">try</span> (Resource3 re3 = <span class="keyword">new</span> Resource3()) &#123;</div><div class="line">        re3.doThing();</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Resource3</span> <span class="keyword">implements</span> <span class="title">AutoCloseable</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doThing</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> Exception(<span class="string">"doThing throw exception"</span>);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">close</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> Exception(<span class="string">"close throw exception"</span>);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>执行结果：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">java.lang.Exception: doThing <span class="keyword">throw</span> exception</div><div class="line">	at com.zxy.lab.code.test.AutoCloseTest$Resource3.doThing(AutoCloseTest.java:<span class="number">61</span>)</div><div class="line">	at com.zxy.lab.code.test.AutoCloseTest.testThrowException(AutoCloseTest.java:<span class="number">50</span>)</div><div class="line">    ...</div><div class="line">	Suppressed: java.lang.Exception: close <span class="keyword">throw</span> exception</div><div class="line">		at com.zxy.lab.code.test.AutoCloseTest$Resource3.close(AutoCloseTest.java:<span class="number">66</span>)</div><div class="line">		at com.zxy.lab.code.test.AutoCloseTest.testThrowException(AutoCloseTest.java:<span class="number">52</span>)</div></pre></td></tr></table></figure></p>
<p>从以上异常信息可以看到，对外抛出的异常时try语句块中的异常，同时try-with-resource抛出的异常会使用addSuppressed方法，将之前的异常记录下来。我们可以在自己的代码中调用getSuppressed方法去获取异常列表并处理，所以这才是我们想要的结果。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">for</span> (Throwable throwable : e.getSuppressed()) &#123;</div><div class="line">    System.out.println(throwable.getMessage());</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>Java7之前同时抛出异常测试：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Test</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testThrowException3</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">    Resource3 re3 = <span class="keyword">null</span>;</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        re3 = <span class="keyword">new</span> Resource3();</div><div class="line">        re3.doThing();</div><div class="line"></div><div class="line">    &#125; <span class="keyword">finally</span> &#123;</div><div class="line">        <span class="keyword">if</span> (re3 != <span class="keyword">null</span>) &#123;</div><div class="line">            re3.close();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Resource3</span> <span class="keyword">implements</span> <span class="title">AutoCloseable</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doThing</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> Exception(<span class="string">"doThing throw exception"</span>);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">close</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> Exception(<span class="string">"close throw exception"</span>);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>结果：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">java.lang.Exception: close <span class="keyword">throw</span> exception</div><div class="line"></div><div class="line">	at com.zxy.lab.code.test.AutoCloseTest$Resource3.close(AutoCloseTest.java:<span class="number">106</span>)</div><div class="line">	at com.zxy.lab.code.test.AutoCloseTest.testThrowException3(AutoCloseTest.java:<span class="number">92</span>)</div><div class="line">	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)</div><div class="line">	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:<span class="number">57</span>)</div><div class="line">	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:<span class="number">43</span>)</div><div class="line">    ...</div></pre></td></tr></table></figure></p>
<p>可见，对外只抛出了finally块中异常，这不是我们想要的。</p>
<h2 id="Closeable和AutoColseable接口"><a href="#Closeable和AutoColseable接口" class="headerlink" title="Closeable和AutoColseable接口"></a>Closeable和AutoColseable接口</h2><p>Closeable接口是jdk5中添加的，AutoColseable则是jdk7才添加的：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"> * <span class="meta">@since</span> <span class="number">1.5</span></div><div class="line"> */</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Closeable</span> <span class="keyword">extends</span> <span class="title">AutoCloseable</span> </span></div><div class="line"></div><div class="line"> * @<span class="title">since</span> 1.7</div><div class="line"> */</div><div class="line"><span class="title">public</span> <span class="title">interface</span> <span class="title">AutoCloseable</span></div><div class="line">    /**</div><div class="line">     * <span class="title">Closes</span> <span class="title">this</span> <span class="title">resource</span>, <span class="title">relinquishing</span> <span class="title">any</span> <span class="title">underlying</span> <span class="title">resources</span>.</div><div class="line">     * <span class="title">This</span> <span class="title">method</span> <span class="title">is</span> <span class="title">invoked</span> <span class="title">automatically</span> <span class="title">on</span> <span class="title">objects</span> <span class="title">managed</span> <span class="title">by</span> <span class="title">the</span></div><div class="line">     * &#123;<span class="meta">@code</span> <span class="keyword">try</span>&#125;-with-resources statement.</div></pre></td></tr></table></figure></p>
<p>AutoCloseable接口对Java7中新增特性try-with-resources提供了支持，只有实现了AutoCloseable接口的类的对象才可以由带资源的try语句进行管理。<br>这个两个接口都只有一个close()方法。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">void</span> <span class="title">close</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span></div></pre></td></tr></table></figure></p>
<p>通过这个方法关闭调用对象，释放可能占用的所有资源。try-with-resources会自动调用该方法关闭资源。</p>
<p>Closeable接口也定义了close()方法。实现了Closeable接口的类的对象可以被关闭。从Java7开始，Closeable扩展了AutoCloseable。因此，在Java7中，所有实现了Closeable接口的类也都实现了AutoCloseable接口。</p>

        
        </div>
		
			<div id="donate" style="text-align:center">
			<div class="post-donate" style="margin-bottom: 30px;margin-top: 10px;">
    <div id="donate_board" class="donate_bar center">
        <a id="btn_donate" class="btn_donate" href="javascript:;" title="donate"></a>
        <span class="donate_txt">
           欣赏此文？求鼓励，求支持！
        </span>
        <br>
    </div>
    <div id="donate_guide" class="donate_bar donate_bar2 center hidden">
        
        <img src="/css/images/alipay.jpg" id="weixin" title="alipay doante" alt="alipay doante">        
        

        
        <img src="/css/images/wechatpay.jpg" title="wechatpay donate" id="zhifubao" alt="echatpay donate">        
        
    </div>
    <script type="text/javascript">
        $('#weixin').hover()
        document.getElementById('btn_donate').onclick = function () {
            $('#donate_board').addClass('hidden');
            $('#donate_guide').removeClass('hidden');
        }

    </script>
</div>
			</div>
		
        <footer class="article-footer">
            
            <div class="share-container">


    <div class="bdsharebuttonbox">
    <a href="#" class="bds_more" data-cmd="more">分享到：</a>
	<a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信">微信</a>
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博">微博</a>
	<!--
    <a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博">腾讯微博</a>
    <a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网">人人网</a>
	<a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间">QQ空间</a>
	-->
    
</div>
<script>
window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{"bdSize":16}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>
<style>
    .bdshare_popup_box {
        border-radius: 4px;
        border: #e1e1e1 solid 1px;
    }
    .bdshare-button-style0-16 a,
    .bdshare-button-style0-16 .bds_more {
        padding-left: 20px;
        margin: 6px 10px 6px 0;
    }
    .bdshare_dialog_list a,
    .bdshare_popup_list a,
    .bdshare_popup_bottom a {
        font-family: 'Microsoft Yahei';
    }
    .bdshare_popup_top {
        display: none;
    }
    .bdshare_popup_bottom {
        height: auto;
        padding: 5px;
    }
</style>


</div>

            
            
    
        <a href="http://menote.info/2016/04/21/Java7新特性：try-with-resources自动关闭资源/#comments" class="article-comment-link">Comments</a>
    

        </footer>
    </div>
    
        
<nav id="article-nav">
    
        <a href="/2016/04/29/Hexo-icarus主题小功能设置/" id="article-nav-newer" class="article-nav-link-wrap">
            <strong class="article-nav-caption">Newer</strong>
            <div class="article-nav-title">
                
                    Hexo icarus主题小功能设置
                
            </div>
        </a>
    
    
        <a href="/2016/04/20/缓存穿透及雪崩之常见解决方案/" id="article-nav-older" class="article-nav-link-wrap">
            <strong class="article-nav-caption">Older</strong>
            <div class="article-nav-title">缓存穿透及雪崩之常见解决方案</div>
        </a>
    
</nav>


    
</article>


    
    <section id="comments">
    
        
		<div id="cloud-tie-wrapper" class="cloud-tie-wrapper"></div>
		<style>
			#yun-tie-sdk-wrap {
				padding: 0;
				background: none;
			}
			#yun-tie-sdk-wrap .tie-tab-bar {
				margin: 5px;
				border-bottom: 1px solid #dee4e9;
			
			}
			#yun-tie-sdk-wrap .tie-title-bar {
				padding: 0px;
			}
			#yun-tie-sdk-wrap .tie-title-bar .tie-title {
				font-size: 18PX;
				font-weight: inherit;
			}
			#yun-tie-sdk-wrap .input-box .tie-submit-row {
				position: relative;
				height: 40px;
				background-color: #f7f8f9
			}
			#yun-tie-sdk-wrap .input-box .tie-submit-row .tie-submit-btn {
				background-color: #e84d1c;
			}
			#yun-tie-sdk-wrap .tie-tab-bar li.z-fcs {
				border: 0px;
				background-color: inherit;
			}
			#yun-tie-sdk-wrap .tie-tab-bar li.z-fcs span {
				color: #e84d1c;
			}

			#yun-tie-sdk-wrap .tie-panel-bar .tie-empty-tip {
				padding: 20px 0px;
			}
		</style>
		
    
    </section>

</section>
            
                <aside id="sidebar">
   
        
    <div class="widget-wrap">
        <h3 class="widget-title"><i class="fa fa-book"></i>recent</h3>
        <div class="widget">
            <ul id="recent-post" class="">
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2016/04/29/Hexo-icarus主题小功能设置/" class="thumbnail">
    
    
        <span class="thumbnail-image thumbnail-none"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/杂谈/">杂谈</a></p>
                            <!--<p class="item-title"><a href="/2016/04/29/Hexo-icarus主题小功能设置/" class="title">Hexo icarus主题小功能设置</a></p>-->
                            <p class="item-title"><a href="/2016/04/29/Hexo-icarus主题小功能设置/" class="title">Hexo icarus主题小功能设置</a></p>
                            <p class="item-date"><time datetime="2016-04-29T03:05:56.000Z" itemprop="datePublished">2016-04-29</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2016/04/21/Java7新特性：try-with-resources自动关闭资源/" class="thumbnail">
    
    
        <span class="thumbnail-image thumbnail-none"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/java/">java</a></p>
                            <!--<p class="item-title"><a href="/2016/04/21/Java7新特性：try-with-resources自动关闭资源/" class="title">Java7新特性：try-with-resources自动关闭资源</a></p>-->
                            <p class="item-title"><a href="/2016/04/21/Java7新特性：try-with-resources自动关闭资源/" class="title">Java7新特性：try-with-resources...</a></p>
                            <p class="item-date"><time datetime="2016-04-21T08:42:46.000Z" itemprop="datePublished">2016-04-21</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2016/04/20/缓存穿透及雪崩之常见解决方案/" class="thumbnail">
    
    
        <span class="thumbnail-image thumbnail-none"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/redis/">redis</a></p>
                            <!--<p class="item-title"><a href="/2016/04/20/缓存穿透及雪崩之常见解决方案/" class="title">缓存穿透及雪崩之常见解决方案</a></p>-->
                            <p class="item-title"><a href="/2016/04/20/缓存穿透及雪崩之常见解决方案/" class="title">缓存穿透及雪崩之常见解决方案</a></p>
                            <p class="item-date"><time datetime="2016-04-20T07:33:49.000Z" itemprop="datePublished">2016-04-20</time></p>
                        </div>
                    </li>
                
            </ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title"><i class="fa fa-folder"></i>categories</h3>
        <div class="widget">
            <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/git/">git</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/java/">java</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/redis/">redis</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/杂谈/">杂谈</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/设计模式/">设计模式</a><span class="category-list-count">1</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title"><i class="fa fa-archive"></i>archives</h3>
        <div class="widget">
            <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/04/">April 2016</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/03/">March 2016</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/02/">February 2016</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/09/">September 2015</a><span class="archive-list-count">1</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title"><i class="fa fa-tags"></i>tag cloud</h3>
        <div class="widget tagcloud">
            <a href="/tags/AutoCloseable/" style="font-size: 10px;">AutoCloseable</a> <a href="/tags/Closeable/" style="font-size: 10px;">Closeable</a> <a href="/tags/git/" style="font-size: 10px;">git</a> <a href="/tags/hexo/" style="font-size: 15px;">hexo</a> <a href="/tags/redis/" style="font-size: 20px;">redis</a> <a href="/tags/sentinel/" style="font-size: 10px;">sentinel</a> <a href="/tags/sentinel原理/" style="font-size: 10px;">sentinel原理</a> <a href="/tags/spring-data-redis/" style="font-size: 10px;">spring-data-redis</a> <a href="/tags/try-with-resources/" style="font-size: 10px;">try-with-resources</a> <a href="/tags/打赏/" style="font-size: 10px;">打赏</a> <a href="/tags/缓存穿透/" style="font-size: 10px;">缓存穿透</a> <a href="/tags/缓存雪崩/" style="font-size: 10px;">缓存雪崩</a> <a href="/tags/设计模式/" style="font-size: 10px;">设计模式</a>
        </div>
    </div>

    
        
    <div class="widget-wrap widget-list">
        <h3 class="widget-title"><i class="fa fa-link"></i>links</h3>
        <div class="widget">
            <ul>
                
                    <li>
                        <a href="http://www.liaoxuefeng.com" target="_blank">廖雪峰</a>
                    </li>
                
                    <li>
                        <a href="http://www.ruanyifeng.com/blog/" target="_blank">阮一峰</a>
                    </li>
                
                    <li>
                        <a href="http://coolshell.cn/" target="_blank">酷壳</a>
                    </li>
                
                    <li>
                        <a href="http://jinnianshilongnian.iteye.com/" target="_blank">开涛的博客</a>
                    </li>
                
            </ul>
        </div>
    </div>


    
    <div id="toTop" class="fa fa-angle-up"></div>
</aside>
            
        </div>

        

        <footer id="footer">
    <div class="outer">
        <div id="footer-info" class="inner">
            &copy; 2017 Mickole Chou<br>
            Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>. Theme by <a href="http://github.com/ppoffice">PPOffice</a>
			.
Analyse with <script src="https://s4.cnzz.com/z_stat.php?id=1261832340&web_id=1261832340" language="JavaScript"></script>

        </div>
    </div>
</footer>
        
    
	<script>
		var cloudTieConfig = {
			url: document.location.href,
			sourceId: "",
			productKey: "undefined",
			target: "cloud-tie-wrapper"
		};
	</script>
	<script src="https://img1.cache.netease.com/f2e/tie/yun/sdk/loader.js"></script>
	



    
        <script src="/libs/lightgallery/js/lightgallery.min.js"></script>
        <script src="/libs/lightgallery/js/lg-thumbnail.min.js"></script>
        <script src="/libs/lightgallery/js/lg-pager.min.js"></script>
        <script src="/libs/lightgallery/js/lg-autoplay.min.js"></script>
        <script src="/libs/lightgallery/js/lg-fullscreen.min.js"></script>
        <script src="/libs/lightgallery/js/lg-zoom.min.js"></script>
        <script src="/libs/lightgallery/js/lg-hash.min.js"></script>
        <script src="/libs/lightgallery/js/lg-share.min.js"></script>
        <script src="/libs/lightgallery/js/lg-video.min.js"></script>
    
    
        <script src="/libs/justified-gallery/jquery.justifiedGallery.min.js"></script>
    
    



<!-- Custom Scripts -->
<script src="https://cdn.jsdelivr.net/clipboard.js/1.6.0/clipboard.min.js"></script>
<script src="/js/main.js"></script>
<script src="/js/copycode.js"></script>

    </div>
</body>
</html>